// src/middleware/redirect-to-login.global.ts
import { useAuthStore } from '@/stores/auth.store';

export default defineNuxtRouteMiddleware((to) => {
  // Skip middleware on server side
  if (process.server) return;

  const authStore = useAuthStore();
  // Check both store and localStorage for token on client-side
  const hasTokenInLocalStorage = typeof window !== 'undefined' && !!localStorage.getItem('auth_token');
  const isAuthenticated = !!authStore.token || hasTokenInLocalStorage;

  console.log(`Middleware: Navigating to ${to.path}, Authenticated: ${isAuthenticated}`);

  // If user is not authenticated and tries to access root, redirect to login
  // 增加对根路径的严格匹配
  // 处理根路径重定向逻辑
  if (to.path === '/') {
    if (!isAuthenticated) {
      return navigateTo('/login', { replace: true });
    } else {
      return navigateTo('/chat', { replace: true });
    }
  }

  // If user is authenticated and tries to access login or register page, redirect to root
  if (isAuthenticated && (to.path === '/login' || to.path === '/register')) {
    console.log(`Middleware: Authenticated, redirecting from ${to.path} to /`);
    return navigateTo('/', { replace: true });
  }

  // Allow navigation otherwise
});